package com.anlu.concurrent.ch6;

import com.anlu.concurrent.utils.SleepTools;

import java.util.Random;
import java.util.concurrent.*;

/**
 * <p>
 * Description:TODO 详细描述
 * <p>
 * Copyright: 天津联想协同科技有限公司
 * <p>
 *
 * @author anlu
 * @date 2021/10/27 17:14
 */
public class UseThreadPool {

    // 工作线程
   static  class Worker implements Runnable{
       private String taskName;
       private Random r = new Random();

        public Worker(String taskName){
            this.taskName = taskName;
        }

        public String getName() {
            return taskName;
        }

       @Override
       public void run() {
           System.out.println(Thread.currentThread().getName()
                   +" process the task : " + taskName);
           SleepTools.ms(r.nextInt(100)*5);
       }
   }


  static class  CallWorker implements Callable<String>{
      private String taskName;
      private Random r = new Random();

      public CallWorker(String taskName){
          this.taskName = taskName;
      }

      public String getName() {
          return taskName;
      }


      @Override
      public String call() throws Exception {
          System.out.println(Thread.currentThread().getName()
                  +" process the task : " + taskName);
          return Thread.currentThread().getName()+":"+r.nextInt(100)*5;
      }

      public static void main(String[] args) throws InterruptedException, ExecutionException {
          ExecutorService pool = Executors.newCachedThreadPool();//其实是比较少
          for(int i=0;i<6;i++) {
              Worker worker = new Worker("worker_"+i);
              pool.execute(worker);
          }
          for(int i=0;i<6;i++) {
              CallWorker callWorker = new CallWorker("callWorker_"+i);
              Future<String> result = pool.submit(callWorker);
              System.out.println(result.get());
          }
          pool.shutdown();
      }
  }
}
